

//  1 分页的实现
//   每页显示多少条数据
//   显示第几页

let page = 1;
// 每页显示的数据
let showSize = 5;

let pageTotal = 0;

let type = '';



// 分类
$('.goods_type input').onclick = function (e) {
    var ev = e || event;
    // 兼容低版本IE
    const target = ev.target || ev.srcElement;

    if (target.tagName === 'INPUT') {
        type = target.innerHTML;
        // 每次分类的时候，都显示第一页的数据
        page = 1;
        getData()
    }
}


// 上翻页
$('.prev').onclick = function () {
    // 判断能不能点
    if (!this.className.includes('disabled')) {
        page--;
        getData();
        // 把下翻页的disabled去掉
        if (this.nextElementSibling.nextElementSibling.className.includes('disabled')) {
            this.nextElementSibling.nextElementSibling.classList.remove('disabled');
        }
        // 超过最大页数
        if (page === 1) {
            this.classList.add('disabled');
        }
    }
}


// 下翻页
$('.next').onclick = function () {
    // 判断能不能点
    if (!this.className.includes('disabled')) {
        page++;
        getData();
        // 把上翻页的disabled去掉
        if (this.previousElementSibling.previousElementSibling.className.includes('disabled')) {
            this.previousElementSibling.previousElementSibling.classList.remove('disabled');
        }
        // 超过最大页数
        if (page === pageTotal) {
            this.classList.add('disabled');
        }
    }
}


async function getData() {
    const res = await myPage({
        page,
        showSize,
        type
    })
    console.log(res);
    const { status, msg, data: list, pageAll } = res;
    if (status) {
        let str = '';
        list.forEach(v => {
            str += `
            <li data-id="${v.id}">
                <a href="./details.html?id=${v.id}">
                    <img src="${v.img}" alt="">
                    <h3>${v.title}</h3>
                    <p class ="dta">${v.des}</p>
                    <div class ="money">
                    <p>￥<span class ="qian">${v.price}</span></p>
                    <p class="xiao">销量: <span class ="liang">${v.sales}</span>w+</p>
                    </div>
                </a>
                <span class="li_cart">加入购物车</sapn>
            </li >
            `
        })

        $('ul').innerHTML = str;

        // 分页的数据不一定能被整除
        pageTotal = Math.ceil(pageAll / showSize);

        if (pageTotal == 1) {
            // 直接把分页隐藏掉
            // 把下翻页加上disabled
            $('.next').classList.add('disabled');
        } else {
            $('.next').classList.remove('disabled');
        }

        // 页数到了最后一页，不能请求
        if (page === pageTotal) {
            $('.next').classList.add('disabled');
        }

        $('.pageAll').innerHTML = page + '/' + pageTotal;
    } else {
        alert(msg)
    }
}

